# 装饰器 decorator

# def name(beizhuangshi_fangfa):
#     def wrapper():
#         a = beizhuangshi_fangfa()
#         print(a)
#     return wrapper
# @name  本质上是   beizhuangshi_fangfa = name(beizhuangshi_fangfa)

# 被装饰的函数有参数
# 装饰器有参数  本质上是 beizhuangshi_fangfa = (name(para))(beizhuangshi_fangfa)
#  装饰器装饰后，本质上是调用的wrapper函数，如果被装饰的函数有参数，装饰器也要接收这些参数


def zhuangshiqi(funcc):
    def wrapper(*paras):
        a = funcc(*paras)
        return f'woshi:{a}'
    return wrapper

#这也是个装饰器，
def zhuangshiqi2(funcc):
    pass
    return funcc

@zhuangshiqi   #   fun1 = zhuangshiqi(fun1)
def fun1(para1):
    return(para1)

@zhuangshiqi
def fun2(para2,para3):
    return(f'{para2}{para3}')

a = fun2('cpy','cpp')
print(a)


# 装饰器有参数
# 名为 zsq   参数为1时，结果加上“你好” ，参数为2时，结果加上“再见”


def zsq(para1):
    def wrapper1(fun):
        def wrapper2(*args):
            a = fun(*args)
            if para1 == 1:
                return f'你好：{a}'
            elif para1 == 2:
                return f'再见：{a}'
        return wrapper2
    return wrapper1


@zsq(1)      #  fun3 = zsq(1)(fun3)
def fun3(para1):
    return(para1)

@zsq(2)
def fun4(para2,para3):
    return(f'{para2}{para3}')

print(fun3('cpy'))

#练习
def retry(max_attempts):  # 外层：接收重试次数参数
    def decorator(func):  # 中层：接收被装饰函数
        def wrapper(*args, **kwargs):
            attempts = 0
            while attempts < max_attempts:
                try:
                    return func(*args, **kwargs)
                except Exception:
                    attempts += 1
            raise TimeoutError(f"超过最大重试次数 {max_attempts}")
        return wrapper
    return decorator

@retry(max_attempts=3)  # 允许最多重试3次
def connect_to_server():
    print("尝试连接服务器...")
    raise ConnectionError("连接失败")



def decorator1(fun):

    def wrapper(*args,**kwargs):

        self_obj = args[0]
        print(f"self_obj是{self_obj}")

        fun(*args,**kwargs)
    return wrapper


class TT:

    @decorator1
    def jj(self):
        print('执行jj方法')


t = TT()
t.jj()

@decorator1
def jjj(para):
    print('执行jjj方法')

jjj(1)